<script setup lang="ts">
import {onBeforeMount, ref, reactive} from "vue";
import type {Ref} from "vue";
import {createUser, deleteUser, pageUser} from "@/api/user";
import type {UserResponse, PageUserRequest, UserRequest} from "@/api/user";
import {Delete, Search} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import type {FormInstance, FormRules} from "element-plus";

const userData: Ref<UserResponse[]> = ref([])
const pageUserRequest: Ref<PageUserRequest> = ref({
  pageIndex: 1,
  pageSize: 10
})
const total: Ref<number> = ref(0)
const isAdminOptions = [
  {
    value: 1,
    label: '是',
  },
  {
    value: 0,
    label: '否',
  }
]
const dialogVisible = ref(false)
const createUserRequest: Ref<UserRequest> = ref({})
const createUserRef = ref<FormInstance>()

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '' || value === null || value === undefined) {
    callback(new Error('请输入密码！'))
  } else if (value.length < 6) {
    callback(new Error("密码长度小于6！"))
  } else {
    callback()
  }
}
const createUserRules = reactive<FormRules>({
  username: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入用户名！',
    }
  ],
  password: [
    {
      required: true,
      validator: validatePassword,
      trigger: 'blur',
    }
  ],
  isAdmin: [
    {
      required: true,
      trigger: 'change',
      message: '请选择是否管理员！',
    }
  ]
})

onBeforeMount(() => {
  pageUserData()
})

function pageUserData(): void {
  pageUser(pageUserRequest.value).then(res => {
    total.value = Number(res.data.total);
    userData.value = res.data.body
  })
}

function currentChange(value: number): void {
  pageUserRequest.value.pageIndex = value
  pageUserData()
}

function removeUser(id: number) {
  deleteUser(id).then(() => {
    ElMessage.success("删除成功")
    pageUserData()
  })
}

function close(createUserRef: FormInstance | undefined) {
  if (!createUserRef) return
  createUserRef.resetFields()
  createUserRequest.value = {}
}

function createUserData() {
  if (!createUserRef.value) return
  createUserRef.value.validate((valid) => {
    if (valid) {
      createUser(createUserRequest.value).then(() => {
        pageUserData()
        dialogVisible.value = false
      })
    }
  })
}
</script>

<template>
  <el-row>
    <el-input v-model="pageUserRequest.username" placeholder="用户名" clearable/>
    <el-select v-model="pageUserRequest.isAdmin" clearable placeholder="是否管理员">
      <el-option v-for="item in isAdminOptions" :key="item.value" :label="item.label" :value="item.value"/>
    </el-select>
    <el-button type="primary" :icon="Search" @click="pageUserData">搜索</el-button>
    <el-button type="primary" @click="dialogVisible = true">创建用户</el-button>
  </el-row>
  <el-table max-height="60vh" :data="userData" empty-text="暂无数据">
    <el-table-column min-width="100px" prop="username" label="用户名"/>
    <el-table-column min-width="100px" prop="isAdmin" label="是否管理员"
                     :formatter="(row:any) => row.isAdmin ? '是' : '否'"/>
    <el-table-column min-width="100px" prop="createDatetime" label="创建时间"/>
    <el-table-column min-width="100px" label="操作">
      <template #default="scope">
        <el-popconfirm title="确认要删除此用户吗？" confirm-button-text="确认" cancel-button-text="取消"
                       confirm-button-type="danger" @confirm="removeUser(scope.row.id)">
          <template #reference>
            <el-button type="danger" size="small" plain :icon="Delete">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination layout="prev, pager, next" :page-size="pageUserRequest.pageSize" :total="total"
                 :current-page="pageUserRequest.pageIndex" @current-change="currentChange" hide-on-single-page/>
  <el-dialog v-model="dialogVisible" title="创建用户" @closed="close(createUserRef)"
             @open="createUserRequest.isAdmin = 0" width="800">
    <el-form ref="createUserRef" :rules="createUserRules" :inline="true" :model="createUserRequest"
             label-width="auto">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="createUserRequest.username" placeholder="用户名" clearable/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="createUserRequest.password" placeholder="密码" clearable/>
      </el-form-item>
      <el-form-item label="是否管理员" prop="isAdmin">
        <el-select v-model="createUserRequest.isAdmin" placeholder="是否管理员">
          <el-option v-for="item in isAdminOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createUserData">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-input {
  width: 230px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.el-select {
  width: 230px;
  margin-right: 10px;
}

.el-table {
  width: 100%;
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
}
</style>